﻿using DDS.IoT.Com;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DDS.IoT.DJ
{
    public class Os2Driver : ComBase
    {
        public override string Type => "DJ_Os2";

        public override string Name => "顶尖OS2";
        private object _locker = new object();

        public override bool Init(int port, int baudRate = 9600, string extendData = null)
        {
            if (SP == null)
            {
                this.Port = port;
                var portName = "COM" + port;
                SP = new SerialPort(portName);
                base.PortName = portName;
                SP.BaudRate = baudRate;
                SP.Parity = System.IO.Ports.Parity.None;
                SP.DataBits = 8;
                SP.StopBits = System.IO.Ports.StopBits.One;
                //SP.DtrEnable = true;
                //SP.RtsEnable = true;
                SP.DataReceived += SP_DataReceived;
                Console.WriteLine("初始化Os2驱动程序成功！");
            }
            return true;
        }

        private void SP_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                lock (_locker)
                {
                    if (false == SP.IsOpen) return;
                    int bytesRead = SP.BytesToRead;//获取接收缓冲区中数据的字节数
                    if (bytesRead < 16)
                    {
                        return;
                    }
                    byte[] bytesData = new byte[16];
                    //var strData = "1,2,83,45,48,48,46,48,49,56,107,103,101,3,4,0";
                    SP.Read(bytesData, 0, 16);
                    if (bytesData[0] != 0x01)
                    {
                        SP.DiscardInBuffer();
                        return;
                    }
                    List<byte> buffer = new List<byte>();
                    buffer.AddRange(bytesData);
                    SP.DiscardInBuffer();
                    var weight = ConvertWeight(buffer);
                    // 验证数据是否有效，且与上一次数据不一致
                    if (weight != this.Data)
                    {
                        if (this.OnPushData != null)
                        {
                            this.OnPushData(this.Id,weight);// 触发事件
                            this.Data = weight;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("串口操作失败：" + ex.Message);
            }
        }

        /// <summary>
        /// Os2称重数据--读取字节为十进制数据 0x为十六进制
        /// </summary>
        /// <param name="byteFrame">帧数据(两位wn+8位数据带小数点+kg+两个固定字节回车换行)</param>
        private float ConvertWeight(List<byte> byteFrame)
        {
            float value = 0f;
            if (byteFrame == null || byteFrame.Count == 0)
            {
                return value;
            }

            if (true)
            {
                byte[] byteData = new byte[9];
                byteFrame.CopyTo(3, byteData, 0, 9);
                string weightData = Encoding.ASCII.GetString(byteData).Replace("kg", "").Replace("g", "");
                value = float.Parse(weightData);
            }
            return value;
        }

        public override event PushData OnPushData;

        public override bool Open()
        {
            var b = false;
            try
            {
                if (!IsOpen)
                    SP.Open();
                b = true;
                IsOpen = true;
            }
            catch (Exception ex)
            {

                string msg = string.Format("Os2串口打开失败：{0} ", ex.Message);
                Console.WriteLine(msg);
            }
            return b;
        }

        public override bool Close()
        {
            if (SP.IsOpen)
                SP.Close();
            IsOpen = false;
            OnPushData = null;
            return true;
        }


    }
}
